﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using Entities;

namespace Logic
{
	public class TMDBAPI
	{
		private string API_KEY;
		private System.Net.WebClient Web = new System.Net.WebClient();

		public TMDBAPI(string apikey)
		{
			API_KEY = apikey;
		}

		private string GetPartialMovieName(string movieName)
		{
			string moviepartialname = "";
			try
			{
				string URL = "http://www.google.com/cse?cx=008177178803676006601:mrme5orikjy&cof=FORID:9&ie=ISO-8859-1&q=" + movieName;

				StreamReader sr = new StreamReader(Web.OpenRead(URL));
				string content = sr.ReadToEnd();

				sr.Close();
				sr.Dispose();

				Regex re = new Regex("http://www\\.filmaffinity\\.com/es/film(_?\\w*)*\\.html", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

				MatchCollection matches = re.Matches(content);

				if (matches.Count > 0)
				{
					StreamReader sr2 = new StreamReader(Web.OpenRead(matches[0].Value.Trim().Replace("/es/", "/en/")));
					string html = sr2.ReadToEnd();

					sr2.Close();
					sr2.Dispose();

					Regex re2 = new Regex("<title>.*</title>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

					MatchCollection matches2 = re2.Matches(html);

					if (matches2.Count > 0)
					{
						moviepartialname = matches2[0].Value.Replace("<title>", "").Replace("</title>", "").Replace(" - FilmAffinity", "").Replace("(TV)", "");
						moviepartialname = Regex.Replace(moviepartialname, "\\(\\d{4}\\)$", "").Trim();
					}
				}
			}
			catch (Exception e)
			{
			}
			return moviepartialname;
		}

		private List<string> GetPartialMoviesName(string movieName)
		{
			List<string> PartialNames = new List<string>();

			try
			{
				string URL = "http://www.google.com/cse?cx=008177178803676006601:mrme5orikjy&cof=FORID:9&ie=ISO-8859-1&q=" + movieName;

				StreamReader sr = new StreamReader(Web.OpenRead(URL));
				string content = sr.ReadToEnd();

				sr.Close();
				sr.Dispose();

				Regex re = new Regex("http://www\\.filmaffinity\\.com/es/film(_?\\w*)*\\.html", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

				MatchCollection matches = re.Matches(content);

				if (matches.Count > 0)
				{
					for (int i = 0; i < matches.Count; i++)
					{
						sr = new StreamReader(matches[i].Value.Trim().Replace("/es/", "/en/"));
						string html = sr.ReadToEnd();

						sr.Close();
						sr.Dispose();

						Regex re2 = new Regex("<title>.*</title>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

						MatchCollection matches2 = re2.Matches(html);

						if (matches2.Count > 0)
						{
							string moviepartialname = matches2[0].Value.Replace("<title>", "").Replace("</title>", "").Replace(" - FilmAffinity", "");
							moviepartialname = Regex.Replace(moviepartialname, "\\s\\(\\d{4}\\)", "");

							PartialNames.Add(moviepartialname);
						}
					}
				}
			}
			catch (Exception e)
			{
			}

			return PartialNames;
		}

		public Movie GetMovieById(string id)
		{
			Movie Movie = new Movie();

			Movie.Poster = "http://hpneo.com/DoubleFeature/img/poster_default.jpg";

			try
			{
				XmlDocument XMLDoc = new XmlDocument();
				XMLDoc.Load("http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/" + API_KEY + "/" + id);

				Movie.Title = XMLDoc.SelectSingleNode("//movies/movie/name").InnerText;
				Movie.Year = Convert.ToInt32(XMLDoc.SelectSingleNode("//movies/movie/released").InnerText.Substring(0, 4));

				XmlNodeList GenresList = XMLDoc.SelectNodes("//movies/movie/categories/category[@type='genre']");

				for (int i = 0; i < GenresList.Count; i++)
				{
					Genre obj = new Genre();
					obj.Name = GenresList[i].Attributes["name"].Value;

					Movie.Genres.Add(obj);
				}

				XmlNodeList DirectorsList = XMLDoc.SelectNodes("//movies/movie/cast/person[@job='Director']");

				if (DirectorsList.Count > 0)
					Movie.Director = DirectorsList[0].Attributes["name"].Value;

				XmlNodeList PostersList = XMLDoc.SelectNodes("//movies/movie/images/image[@type='poster' and @size='mid']");

				if (PostersList.Count > 0)
					Movie.Poster = PostersList[0].Attributes["url"].Value;
			}
			catch (Exception e)
			{
			}

			return Movie;
		}

		public List<Movie> SearchMovies(string movieTitle, bool searchPartialNames)
		{
			List<Movie> Movies = new List<Movie>();

			string nametosearch = "";

			try
			{
				if (searchPartialNames)
					nametosearch = GetPartialMovieName(movieTitle);
				else
					nametosearch = movieTitle;

				XmlDocument XMLDoc = new XmlDocument();
				XMLDoc.Load("http://api.themoviedb.org/2.1/Movie.search/en/xml/" + API_KEY + "/" + nametosearch);

				XmlNodeList XMLMovie = XMLDoc.GetElementsByTagName("movie");

				for (int i = 0; i < XMLMovie.Count; i++)
				{
					Movies.Add(GetMovieById(((XmlElement)XMLMovie[i]).GetElementsByTagName("id")[0].InnerText));
				}
			}
			catch (Exception e) { }

			return Movies;
		}

		public List<Movie> SearchMovies(string movieTitle)
		{
			return SearchMovies(movieTitle, false);
		}
	}
}